package net.borlis.errors.providers.implementation.enumbase;

import net.borlis.errors.exceptions.ServerException;
import net.borlis.errors.exceptions.TranslatedException;
import net.borlis.errors.providers.common.IServerExceptionProcessor;
import net.borlis.errors.providers.common.ITranslatedExceptionProcessor;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

/**
 * @author alex@borlis.net
 */
@ApplicationScoped @EnumErrors @Deprecated
public class EnumTranslatedExceptionProcessor implements ITranslatedExceptionProcessor {

    private static final String EN_LOCALE = "en-GB";
    private static final String DE_LOCALE = "de-DE";

    @Inject
    private Logger logger;

    @Inject @EnumErrors
    private IServerExceptionProcessor exceptionProcessor;

    @PostConstruct
    public void init(){
        logger.info("init enum based translation");
    }

    @Override
    public TranslatedException newTranslatedException(String locale, ServerException se) {
        return prepareTranslatedException(locale, se);
    }

    @Override
    public TranslatedException newTranslatedException(String locale, String code) {
        return prepareTranslatedException(locale, exceptionProcessor.newServerException(code));
    }

    @Override
    public TranslatedException newTranslatedException(String locale, String code, Throwable cause) {
        return prepareTranslatedException(locale, exceptionProcessor.newServerException(code, cause));
    }

    private TranslatedException prepareTranslatedException(String locale, ServerException se) {
        String translatedMessage;
        if (EN_LOCALE.equals(locale)) {
            translatedMessage = LangEN.findMessageByKey(se.getKeyMaster().getKey());
        } else if (DE_LOCALE.equals(locale)) {
            translatedMessage = LangDE.findMessageByKey(se.getKeyMaster().getKey());
        } else {
            throw new IllegalArgumentException("the locale " + locale + " not supported.");
        }
        return new TranslatedException(se, translatedMessage);
    }

    @Override
    public Set<String> getSupportedLocales() {
        Set<String> result = new HashSet<>();
        result.add(EN_LOCALE);
        result.add(DE_LOCALE);
        return result;
    }

}
